package com.csu.jpetstore_reconfiguration_back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csu.jpetstore_reconfiguration_back.common.CommonResponse;
import com.csu.jpetstore_reconfiguration_back.service.UserService;
import com.csu.jpetstore_reconfiguration_back.domain.User;
import com.csu.jpetstore_reconfiguration_back.mapper.UserMapper;
import com.csu.jpetstore_reconfiguration_back.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author 朱嘉辉
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-04-13 20:22:38
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public CommonResponse<String> login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username).eq("password",password);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null){
            String token =JwtUtil.createToken(user.getUserId().toString(),user.getPassword());
            return CommonResponse.createForSuccess("登录成功",token);
        }
        return CommonResponse.createForError("账号或密码错误");
    }

    @Override
    public CommonResponse<User> register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user.getUsername());
        if(userMapper.selectList(queryWrapper).isEmpty()){
            user.setStatus("OK");
            userMapper.insert(user);
            return CommonResponse.createForSuccess("注册成功",userMapper.selectOne(queryWrapper));
        }
        return CommonResponse.createForError("用户名已存在");
    }

    @Override
    public CommonResponse<User> getCurrentUser(HttpServletRequest request) {
        String token = request.getHeader("token");
        JwtUtil.verifyToken(token);
        return CommonResponse.createForSuccess("成功",JwtUtil.getCurrentUser(token));
    }

    @Override
    public CommonResponse<List<User>> getAllUser() {
        List<User> users = userMapper.selectList(null);
        if (users.isEmpty()){
            return CommonResponse.createForError("没有用户");
        }
        return CommonResponse.createForSuccess("查询成功",users);
    }
}




